<?php

/**
 * Classe d'index, permettant la vérification de la session
 * @singleton
 * @author Rémi
 * @version 2.0
 */
class Index
{
    /**
     * 	Gère les fonctions du site
     */

    /**
     * @var Index
     */
    public static $instance;
    /**
     * @var Utilisateur
     */
    public $global_member;
    /**
     * @var ConnHisto
     */
    public $global_connhist;

    private function __construct()
    {
        $this->global_member = new Utilisateur(0);
        $this->global_connhist = new Connhisto(0);
    }

    /**
     * @static
     * @return Object Index
     */
    public static function getInstance()
    {
        if (!isset(self::$instance))
        {
            $c = __CLASS__;
            self::$instance = new $c;
        }

        return self::$instance;
    }

    /**
     * Permet de connecter un utilisateur en envoyant login/mot de passe
     * @param string $login
     * @param string $password
     * @param int $state
     * @return int code d'erreur
     */
    public function Userlogin($login, $password, $state = 0)
    {
        $errorCode = 0;
        

        //Va chercher l'utilisateur, retourne errorCode si pas trouvé,....
        if (isset($password) && isset($login) && !empty($password) && !empty($login))
        {

            //Transformation du password en md5
            $transPass = md5($password);
            //Instanciation connexion PDO
            $sql = SQL::getInstance()->getConnection();
            //On retourne l'entrée demandée
            if ($state == 0)
            {
                $query = 'SELECT Utilisateur.IdUtilisateur,Utilisateur.StatutUtilisateur FROM Utilisateur WHERE Utilisateur.EmailUtilisateur = :Requestlogin AND Utilisateur.PasswordUtilisateur = :RequestPass';
                $c = $sql->prepare($query);
                $c->bindParam(':Requestlogin', $login, PDO::PARAM_STR);
                $c->bindParam(':RequestPass', $transPass, PDO::PARAM_STR);
            }
            else
            {
                $query = 'SELECT Utilisateur.IdUtilisateur,Utilisateur.StatutUtilisateur  FROM Utilisateur WHERE Utilisateur.EmailUtilisateur = :Requestlogin';
                $c = $sql->prepare($query);
                $c->bindParam(':Requestlogin', $login, PDO::PARAM_STR);
            }

            //Exécution de la requête retourne false si echec
            if ($c->execute())
            {
                //On vérifie que l'on a bien une entrée
                $result = $c->fetch(PDO::FETCH_OBJ);
                if (!empty($result))
                {
                    //on charge le Utilisateur
                    switch ($result->StatutUtilisateur)
                    {
                        case '0':
                            $this->global_member = new Etudiant($result->IdUtilisateur);
                            break;
                        case '1':
                            $this->global_member = new Enseignant($result->IdUtilisateur);
                            break;
                        case '2':
                            $this->global_member = new ContactEntreprise($result->IdUtilisateur);
                            break;
                    }


                    if ($this->global_member->requeteOk)
                    {
                        //Le login est réussi, on met à jour les sessions dans la bdd
                        //On obtient les infos du client
                        $infosClient = $this->getInfosClient();
                        //On crée un objet connHisto
                        $myConnHisto = new Connhisto(0);
                        //On met à jour l'objet avec les infos de $infosClient
                        $myConnHisto->setSID($infosClient["sidget"]);
                        $myConnHisto->setHost($infosClient["hostget"]);
                        $myConnHisto->setClient($infosClient["clientget"]);
                        $myConnHisto->setIdUtilisateur($this->global_member->getIdUtilisateur());
                        $myConnHisto->setDateDerniereConn();
                        $myConnHisto->insertConnHisto();

                        if ($myConnHisto->requeteOk)
                        {
                            $this->global_connhist = $myConnHisto;
                            $errorCode = 0;
                            $this->global_member->setDateDerniereConn();
                            $this->global_member->update();
                        }
                        else
                        {
                            $errorCode = 5; //erreur connhisto
                            if (defined(_DEBUG))
                            {
                                //Une erreur est survenu, envoi du mail a webmaster
                                $mailer = new mailer();
                                $mailer->sendErreur(print_r($myConnHisto->errmsg, true));
                            }
                        }
                    }
                    else
                    {
                        $errorCode = 4; //Erreur création Utilisateur
                        if (defined(_DEBUG))
                        {
                            //Une erreur est survenu, envoi du mail a webmaster
                            $mailer = new mailer();
                            $mailer->sendErreur(print_r($this->global_member->errmsg, true));
                        }
                    }
                }
                else
                {
                    $errorCode = 1; //login ou password pas bon
                }
            }
            else
            {
                $errorCode = 6; //erreur intérrogation sql
                if (defined(_DEBUG))
                {
                    //Une erreur est survenu, envoi du mail a webmaster
                    $mailer = new mailer();
                    $mailer->sendErreur(print_r($c->errorInfo(), true));
                }
            }
        }
        else
        {
            $errorCode = 1; //login ou password pas bon
        }
        return $errorCode;
    }

    /**
     * Obtient l'ip
     * @return string
     */
    public function getIp()
    {
        return $_SERVER['REMOTE_ADDR'];
    }

    /**
     * Obtient le nom du navigateur
     * @return string
     */
    public function getBrowser()
    {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        if ((strpos($user_agent, "Nav") !== FALSE) || (strpos($user_agent, "Gold") !== FALSE) ||
                (strpos($user_agent, "X11") !== FALSE) || (strpos($user_agent, "Mozilla") !== FALSE) ||
                (strpos($user_agent, "Netscape") !== FALSE)
                AND (!strpos($user_agent, "MSIE") !== FALSE)
                AND (!strpos($user_agent, "Konqueror") !== FALSE)
                AND (!strpos($user_agent, "Firefox") !== FALSE)
                AND (!strpos($user_agent, "Safari") !== FALSE))
            $browser = "Netscape";
        elseif (strpos($user_agent, "Opera") !== FALSE)
            $browser = "Opera";
        elseif (strpos($user_agent, "MSIE") !== FALSE)
            $browser = "MSIE";
        elseif (strpos($user_agent, "Lynx") !== FALSE)
            $browser = "Lynx";
        elseif (strpos($user_agent, "WebTV") !== FALSE)
            $browser = "WebTV";
        elseif (strpos($user_agent, "Konqueror") !== FALSE)
            $browser = "Konqueror";
        elseif (strpos($user_agent, "Safari") !== FALSE)
            $browser = "Safari";
        elseif (strpos($user_agent, "Firefox") !== FALSE)
            $browser = "Firefox";
        elseif ((stripos($user_agent, "bot") !== FALSE) || (strpos($user_agent, "Google") !== FALSE) ||
                (strpos($user_agent, "Slurp") !== FALSE) || (strpos($user_agent, "Scooter") !== FALSE) ||
                (strpos($user_agent, "Spider") !== FALSE) || (strpos($user_agent, "Infoseek") !== FALSE))
            $browser = "Bot";
        else
            $browser = "Autre";

        return $browser;
    }

    /*
     * Obtient la chaine agent complet
     * @return string
     */

    public function getAgent()
    {
        return $_SERVER['HTTP_USER_AGENT'];
    }

    /**
     * Obtient les infos du client pour la session
     * @return mixed
     */
    public function getInfosClient()
    {
        $myArray = array("sidget" => "", "hostget" => "", "clientget" => "");
        $myArray["sidget"] = session_id();
        $myArray["hostget"] = $this->getIp();
        $myArray["clientget"] = $this->getAgent();
        return $myArray;
    }

    /**
     * Permet de rediriger le membre aprés reconnection du à un timeout de la session
     * @param string $queryString
     * @return mixed
     */
    public function parseUrl($queryString)
    {
        if (($champs = explode('&', $queryString)) === false)
        {
            return array();
        }
        $resultat = array();
        foreach ($champs as $champ)
        {
            if (($zone = explode('=', $champ, 2)) === false)
            {
                $nom = urldecode($champ);
                $valeur = '';
            }
            else
            {
                $nom = urldecode($zone[0]);
                if (isset($zone[1]))
                {
                    $valeur = urldecode($zone[1]);
                }
                else
                {
                    $valeur = '';
                }
            }
            if (empty($resultat[$nom]))
            {
                $resultat[$nom] = $valeur;
            }
            elseif (!empty($valeur))
            {
                $resultat[$nom] .= ' ' . $valeur;
            }
        }
        return $resultat;
    }

    /*
     * Obtient le chemin vers le template demandé s'il existe
     * Cette fonciton permet de vérifier si la page existe
     * @param string $tpl nom de la page
     * @return string chemin d'accès concernant la page demandée
     */
    public function findTemplate($tpl)
    {
        if (isset($tpl))
        {
            $tabTpl = array(
                // test jey
                "test" => "app/test.php",
                /*                 * ** Etudiant *** */
                "profil_etudiant" => "app/etudiant/profil.php",
                "stage_etudiant" => "app/etudiant/stage.php",
                "submit_offre" => "app/etudiant/offre.php",
                "submit_offre_portail" => "app/etudiant/offre_portail.php",
                "submit_offre_externe" => "app/etudiant/offre_externe.php",
                "fiche" => "app/etudiant/view_fiche.php",
                "stage" => "app/etudiant/view_stage.php",
                "uploadDocument" => "app/etudiant/upload_document.php",
                /*                 * ** Tuteur Enseignant ** */
                "profil_tuteur_enseignant" => "app/enseignant/tuteur/profil.php",
                "currentStages_tuteur_enseignant" => "app/enseignant/tuteur/currentStages.php",
                "pastStages_tuteur_enseignant" => "app/enseignant/tuteur/pastStages.php",
                /*                 * **** Entreprise *** */
                "tuteur_entreprise_stage" => "app/entreprise/tuteur/list.php",
                "tuteur_entreprise_stage_v" => "app/entreprise/tuteur/view.php",
                "app_entreprise_proposeroffre" => "app/entreprise/proposer_offre.php",
                "app_entreprise_viewoffre" => "app/entreprise/view_offre.php",
                "app_entreprise_historiqueoffre" => "app/entreprise/historique_offre.php",
                "app_entreprise_gestionprofil" => "app/entreprise/gestion_profil.php",
                "app_entreprise_gestionprofilentreprise" => "app/entreprise/gestion_profil_entreprise.php",
                /*                 * **** Offres *** */
                "offres" => "app/offres/list.php",
                "view_offre" => "app/offres/view.php",
                
                /*                 * ** ajax **** */
                "ajaxAddEntrepriseInOffre"=>"js/ajax/addEntreprise.php",
                "ajaxAttribution" => "js/ajax/attribution.php",
                "ajaxGetEntrepriseById" => "js/ajax/getEntrepriseById.php",
                "ajaxGetFormOffrePortail" =>"js/ajax/getFormOffrePortail.php",
                "ajaxGetPays" => "js/ajax/getPays.php",
                "ajaxsetSignatureConvention" => "js/ajax/setSignatureConvention.php",
                "ajaxGetContactEntrepriseByEntreprise" => "js/ajax/getContactEntrepriseByEntreprise.php",
                "ajaxGetOffres" => "js/ajax/getOffres.php",
                "ajaxGetEnseignantById" => "js/ajax/getEnseignantById.php",
                "ajaxsetRequiredDocument" => "js/ajax/setRequiredDocument.php",


                /*                 * ********* Admin   *********** */
                "admin" => "backoffice/dashboard.php",
                //User
                "admin_users" => "backoffice/users/index.php",
                "admin_usercontact_list" => "backoffice/users/contacts/list.php",
                "admin_userenseignant_list" => "backoffice/users/enseignants/list.php",
                "admin_useretudiant_list" => "backoffice/users/etudiants/list.php",
                "admin_useredit_etudiant" => "backoffice/users/etudiants/edit.php",
                "admin_useredit_enseignant" => "backoffice/users/enseignants/edit.php",
                "admin_useredit_contact" => "backoffice/users/contacts/edit.php",
                "admin_userview_etudiant" => "backoffice/users/etudiants/view.php",
                "admin_userview_enseignant" => "backoffice/users/enseignants/view.php",
                "admin_userview_contact" => "backoffice/users/contacts/view.php",
                "admin_useradd_etudiant" => "backoffice/users/etudiants/add.php",
                "admin_useradd_enseignant" => "backoffice/users/enseignants/add.php",
                "admin_useradd_contact" => "backoffice/users/contacts/add.php",
                "admin_userimport_etudiant" => "backoffice/users/etudiants/csv.php",
                "admin_useradd_entreprise" => "backoffice/entreprises/add.php",
                "admin_userview_entreprise" => "backoffice/entreprises/view.php",
                "admin_userentreprise_edit" => "backoffice/entreprises/edit.php",
                "admin_userentreprise_list" => "backoffice/entreprises/list.php",
                "admin_userufr_list" => "backoffice/ufr/list.php",
                "admin_userufr_edit" => "backoffice/ufr/edit.php",
                "admin_userufr_add" => "backoffice/ufr/add.php",
                // Offre
                "admin_offres" => "backoffice/offres/list.php",
                "admin_offres_add" => "backoffice/offres/add.php",
                "admin_offres_edit" => "backoffice/offres/edit.php",
                // Fin offre

                /* Stages */
                "admin_stages" => "backoffice/stages/index.php",
                "admin_stages_fiches_valide_list" => "backoffice/stages/fiches/valide/list.php",
                "admin_stages_fiches_valide_view" => "backoffice/stages/fiches/valide/view.php",
                "admin_stages_fiches_attente_list" => "backoffice/stages/fiches/attente/list.php",
                "admin_stages_fiches_attente_view" => "backoffice/stages/fiches/attente/view.php",
                "admin_stages_conventions_list" => "backoffice/stages/conventions/list.php",
                "admin_stages_conventions_view" => "backoffice/stages/conventions/view.php",
                "admin_stages_conventions_edit" => "backoffice/stages/conventions/edit.php",
                "admin_stages_attribution" => "backoffice/stages/fiches/valide/attribution.php",
                /* Fin stages */

                /* Administration */
                "admin_administration" => "backoffice/administration/index.php",
                "admin_administration_doc_administratifs_list" => "backoffice/administration/doc_administratifs/list.php",
                "admin_administration_doc_administratifs_add" => "backoffice/administration/doc_administratifs/add.php",
                "admin_administration_doc_obligatoires" => "backoffice/administration/doc_obligatoires/list.php",
                "admin_administration_doc_obligatoires_add" => "backoffice/administration/doc_obligatoires/add.php",
                "admin_administration_doc_obligatoires_edit" => "backoffice/administration/doc_obligatoires/edit.php",

                "admin_portail" => "backoffice/portail/index.php",
                "admin_portaildomaine_list" => "backoffice/portail/domaine/list.php",
                "admin_portaildomaine_edit" => "backoffice/portail/domaine/edit.php",
                "admin_portaildomaine_add" => "backoffice/portail/domaine/add.php",
                "admin_portailcategorie_list" => "backoffice/portail/categorie/list.php",
                "admin_portailcategorie_edit" => "backoffice/portail/categorie/edit.php",
                "admin_portailcategorie_add" => "backoffice/portail/categorie/add.php",
                "admin_portailcategorie_view" => "backoffice/portail/categorie/view.php",
                "admin_portailtechnologie_list" => "backoffice/portail/technologie/list.php",
                "admin_portailtechnologie_edit" => "backoffice/portail/technologie/edit.php",
                "admin_portailtechnologie_add" => "backoffice/portail/technologie/add.php",

                "admin_options" => "backoffice/options/list.php",
                "admin_options_add" => "backoffice/options/add.php",
                "admin_options_edit" => "backoffice/options/edit.php",

                "admin_dates" => "backoffice/dates/list.php",
                "admin_dates_add" => "backoffice/dates/add.php",
                "admin_dates_edit" => "backoffice/dates/edit.php",

                "admin_mails" => "backoffice/mail/list.php",
                "admin_mails_add" => "backoffice/mail/add.php",
                "admin_mails_edit" => "backoffice/mail/edit.php",
                "admin_mails_test" => "backoffice/mail/test.php",


                // Page resticted Access
                "restricted_access" => "app/restricted.php",
                //Logout
                "logout" => "logout.php"
            );

            //on cherche la correspondance
            if (array_key_exists($tpl, $tabTpl))
            {
                return $tabTpl[$tpl];
            }
            else
            {
                return $this->findPublicTemplate($tpl);
            }
        }
        else
        {
            return "app/accueil.php";
        }
    }

    public function findPublicTemplate($tpl)
    {
        if (isset($tpl))
        {
            $tabTpl = array(
                "home" => "app/accueil.php",
                "infos" => "app/infos.php"
            );
            if (array_key_exists($tpl, $tabTpl))
            {
                return $tabTpl[$tpl];
            }
            else
            {
                return "app/accueil.php";
            }
        }
        else
        {
            return "app/accueil.php";
        }
    }

}
?>

